package com.dragon.framework.interceptor;

import com.dragon.common.annotation.RepeatSubmit;
import com.dragon.common.utils.AjaxResult;
import com.dragon.common.utils.ServletUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.reflect.Method;

/**
 * 重复提交拦截器
 *
 * @author dragon
 * @version 1.0
 * @date 2024/9/25 17:56
 */
@Component
public abstract class RepeatSubmitInterceptor implements HandlerInterceptor {

    @Resource
    private ObjectMapper objectMapper;


    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) throws Exception {
        if (handler instanceof HandlerMethod handlerMethod) {
            Method method = handlerMethod.getMethod();
            RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class);

            if (annotation != null) {
                if (this.isRepeatSubmit(request, annotation)) {
                    AjaxResult<Void> ajaxResult = AjaxResult.failed(annotation.message());
                    ServletUtils.renderString(response, objectMapper.writeValueAsString(ajaxResult));
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 验证是否重复提交由子类实现具体的防重复提交的规则
     *
     * @param request    请求信息
     * @param annotation 防重复注解参数
     * @return 结果
     */
    public abstract boolean isRepeatSubmit(HttpServletRequest request, RepeatSubmit annotation) throws JsonProcessingException;

}
